/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilDate;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.base.utils.UtilLog;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.BaseUIFragment;
import com.ouertech.android.agm.lib.ui.base.FragmentTab;
import com.ouertech.android.agm.lib.ui.base.UIOptions;
import com.ouertech.android.agm.lib.ui.base.defaults.activity.BaseFullActivity;
import com.ouertech.android.agm.lib.ui.base.defaults.activity.BaseSystemActivity;
import com.ouertech.android.agm.lib.ui.base.defaults.activity.BaseTopActivity;
import com.ouertech.android.agm.lib.ui.widget.tabhost.FragmentTabHost;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.UpdateInfo;
import com.simon.mengkou.data.enums.EDirection;
import com.simon.mengkou.data.enums.EOsType;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.constant.CstOuer.KEY;
import com.simon.mengkou.system.constant.CstOuer.BROADCAST_ACTION;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.dialog.AppUpdateDialog;
import com.simon.mengkou.ui.fragment.BuyFragment;
import com.simon.mengkou.ui.fragment.CategoryFragment;
import com.simon.mengkou.ui.fragment.CommunityFragment;
import com.simon.mengkou.ui.fragment.DiscoveryFragment;
import com.simon.mengkou.ui.fragment.EmptyFragment;
import com.simon.mengkou.ui.fragment.HomeFragment;
import com.simon.mengkou.ui.fragment.HomeNewFragment;
import com.simon.mengkou.ui.fragment.MessageFanFragment;
import com.simon.mengkou.ui.fragment.UserFragment;
import com.simon.mengkou.utils.UtilOuer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author : Zhenshui.Xia
 * @date : 2014年8月12日
 * @desc : 主界面
 */
public class MainTabActivity extends BaseSystemActivity
					implements OnTabChangeListener{
	//Tabhost
	@Bind(android.R.id.tabhost)
	FragmentTabHost mTabHost;

	private List<FragmentTab> mNavTabs;
	private long mTotalTime = 0;
	
	private int mIndex;

	@Override
	protected void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		int index = getIntent().getIntExtra(KEY.INDEX, 0);
		mIndex = index == -1 ? 0 : index;

		//首页
		addNavTab(R.string.main_tab_home, 	R.drawable.main_tab_home_bg, 		HomeFragment.class);
		//发现
		addNavTab(R.string.main_tab_discovery, 	R.drawable.main_tab_discovery_bg, CommunityFragment.class);
		//发布
		addNavTab(R.string.main_tab_post, 	0, 		EmptyFragment.class);
		//购买
		addNavTab(R.string.main_tab_buy, 	R.drawable.main_tab_buy_bg, 		MallFragment.class);
		//我的
		addNavTab(R.string.main_tab_user, 	R.drawable.main_tab_user_bg, 		UserFragment.class);
	}


	@Override
	protected void initSystem() {

	}

	@Override
	protected void initLayout() {
		setContentView(R.layout.activity_main_tab);
	}

	@Override
	protected void initViews() {
		ButterKnife.bind(this);

		//初始化Tabhost
		if(UtilList.isNotEmpty(mNavTabs)) {
			mTabHost.setOnTabChangedListener(this);
			mTabHost.setup(this, getSupportFragmentManager(), R.id.main_tab_id_content);

			for (int i = 0; i < mNavTabs.size(); i++) {
				FragmentTab tab = mNavTabs.get(i);
				mTabHost.addTab(mTabHost.newTabSpec(tab.getFragmentClazz().getName())
								.setIndicator(newTabIndicator(tab.getTitle(), tab.getIcon())),
						tab.getFragmentClazz(), null);
			}

			mTabHost.getTabWidget().setDividerDrawable(null);
		}

		//监听tab切换广播
        registerAction(CstOuer.BROADCAST_ACTION.MAINTAB_CHANGED_ACTION);
		//监听登录广播
        registerAction(CstOuer.BROADCAST_ACTION.NEED_LOGIN_ACTION);
		//监听退出广播
        registerAction(CstOuer.BROADCAST_ACTION.UNLOGINED_ACTION);
        
			
        //检查更新
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				backgroundCheckUpgrade();
			}
		}, 3000);
	}


	@Override
	protected void onResume() {
		super.onResume();
		//切换到指定index的TAB界面，默认第一个tab
		mTabHost.setCurrentTab(mIndex);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		//关闭当前所有界面
		boolean exit = intent.getBooleanExtra(KEY.EXIT, false);
		if(exit) {
			//打开登录界面
			OuerDispatcher.presentLoginActivity(this);
			finish();
			return;
		}

		//当前的tab界面
		int index = intent.getIntExtra(KEY.INDEX, 0);
		mIndex = index == -1 ? mIndex : index;
	}

	@Override
	public void onTabChanged(String arg0) {
		//获取当前tab界面的索引
		mIndex = mTabHost.getCurrentTab();
	}
	
	@Override
	protected void onReceive(Intent intent) {
		super.onReceive(intent);
		
		String action = intent.getAction();
		if(CstOuer.BROADCAST_ACTION.MAINTAB_CHANGED_ACTION.equals(action)) { //切换tab
			int index = intent.getIntExtra(CstOuer.KEY.INDEX, 0);
			mIndex = index == -1 ? mIndex : index;
		}  else if(CstOuer.BROADCAST_ACTION.UNLOGINED_ACTION.equals(action)
				|| BROADCAST_ACTION.NEED_LOGIN_ACTION.equals(action) ) {//退出登录
			//退出当前打开的所有界面
			Intent exitIntent = new Intent(this, MainTabActivity.class);
			exitIntent.putExtra(KEY.EXIT, true);
			startActivity(exitIntent);
		}
	}

	//发布帖子
	@OnClick(R.id.main_id_center)
	protected void post() {
		OuerDispatcher.presentCreateActivity(this);
	}

	/**
     * 再按一次退出程序
     */
    @Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - mTotalTime) > 2000) {
				UtilOuer.toast(this, R.string.main_exit);
				mTotalTime = System.currentTimeMillis();
			} else {
				finish();
			}
			
			return true;
		}
		
		return super.dispatchKeyEvent(event);
	}

	/**
	 * 创建tab item
	 * @param txtRes
	 * @param imgRes
	 * @return
	 */
	private View newTabIndicator(@StringRes int txtRes,  @DrawableRes int imgRes) {
		return newTabIndicator(getString(txtRes), imgRes);
	}

	/**
	 * 创建tab item
	 * @param title
	 * @param imgRes
	 * @return
	 */
	private View newTabIndicator(String title, @DrawableRes int imgRes) {
		View indicator = LayoutInflater.from(this)
				.inflate(R.layout.res_layout_base_navbar_tab_indicator, null);
		if(imgRes == 0) {
			indicator.setVisibility(View.INVISIBLE);
		}

		ImageView ivIcon = (ImageView) indicator.findViewById(R.id.base_id_tab_img);
		ivIcon.setBackgroundResource(imgRes);
		TextView tvName = (TextView)indicator.findViewById(R.id.base_id_tab_text);
		tvName.setText(title);
		return indicator;
	}

	/**
	 * 添加navbar的tab item
	 * @param txtRes
	 * @param imgRes
	 * @param cls
	 */
	public void addNavTab(@StringRes int txtRes, @DrawableRes int imgRes, Class<? extends BaseUIFragment> cls) {
		addNavTab(txtRes <=0 ? null : getString(txtRes), imgRes, cls);
	}

	/**
	 * 添加navbar的tab item
	 * @param title
	 * @param imgRes
	 * @param cls
	 */
	public void addNavTab(String title,  @DrawableRes int imgRes, Class<? extends BaseUIFragment> cls) {
		if( UtilString.isNotBlank(title)) {
			if (mNavTabs == null) {
				mNavTabs = new ArrayList<>(4);
			}

			FragmentTab tab = new FragmentTab();
			tab.setTitle(title);
			tab.setIcon(imgRes);
			tab.setFragmentClazz(cls);
			mNavTabs.add(tab);
		}
	}


	/**
	 * 后台静默检查升级
	 */
	public void backgroundCheckUpgrade() {
		final String currDate = UtilDate.formatDate(Calendar.getInstance(), UtilDate.FORMAT_YYYYMMDD);
		String lastDate = OuerApplication.mPreferences.getCheckUpgradeDay();
		if (!currDate.equals(lastDate)) {
			AgnettyFuture future = OuerApplication.mOuerFuture.checkUpgrade(
					OuerApplication.mAppInfo.getVersionCode(),
					EOsType.ANDROID,
					OuerApplication.mAppInfo.getAppChannel(),
					new OuerFutureListener(this) {

						@Override
						public void onComplete(AgnettyResult result) {
							super.onComplete(result);

							UpdateInfo info = (UpdateInfo) result.getAttach();

							if (info == null || !info.isForceUpdate()) {
								OuerApplication.mPreferences.setCheckUpgradeDay(currDate);
							}

							if (info != null) {
								AppUpdateDialog dialog = new AppUpdateDialog(MainTabActivity.this, info);
								dialog.show();
							}
						}

						@Override
						public void onNetUnavaiable(AgnettyResult result) {
							//什么也不提示
						}
					});

			attachDestroyFutures(future);
		}
	}
}
